package com.yuantu.judiciary.serviceimpl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.yuantu.judiciary.common.SysCode;
import com.yuantu.judiciary.dao.ISysOperLogApiDao;
import com.yuantu.judiciary.exception.ServiceException;
import com.yuantu.judiciary.model.api.BaseApiRequestMsg;
import com.yuantu.judiciary.model.api.BaseApiResponseMsg;
import com.yuantu.judiciary.model.domain.SysOperLogApiDO;
import com.yuantu.judiciary.model.enums.SearchType;
import com.yuantu.judiciary.service.IOpenApiRequestService;
import com.yuantu.judiciary.utils.AesUtil;
import com.yuantu.judiciary.utils.AssertUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StopWatch;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 外部接口实现
 *
 * @author syw
 * @since 2023-06-30
 **/
@Service
@Slf4j
@RequiredArgsConstructor
public class OpenApiRequestServiceImpl implements IOpenApiRequestService<BaseApiRequestMsg, BaseApiResponseMsg> {

    private static final String IP = "http://123.124.130.19/qysstest";
//    private static final String IP = "https://qyss.cjbdi.com/qyss";
    private static final int SUCCESS_CODE = 1000;
    private static final String HEADER_CONTENT_TYPE = "application/json;charset=UTF-8";
    private static final String HEADER_TICKET = "KL8dptA34tYH1Uclpg0+dbJqwKoemR0hszDcTz4lZvE=";
//    private static final String HEADER_TICKET = "UYS0JdEHE1J7wkc4Bm2JFADie5uLmjqlgztxMC8HOI0=";
    private static final String KEY = "xykjg&aE8jc2qitg";
//    private static final String KEY = "xucsg&aEjI2cxchg";

    private final ISysOperLogApiDao logApiDao;


    @Override
    public BaseApiResponseMsg emitHttpRequest(BaseApiRequestMsg msg) throws ServiceException {
        String url = StringUtils.isNotBlank(msg.getTotalUrl()) ? msg.getTotalUrl() : IP + msg.getUrl();

        Map<String, String> header = new HashMap<>(8);
        header.put("Content-Type", HEADER_CONTENT_TYPE);
        header.put("ticket", StringUtils.isNotBlank(msg.getTicket()) ? msg.getTicket() : HEADER_TICKET);
        String key = StringUtils.isNotBlank(msg.getKey()) ? msg.getKey() : KEY;

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        String requestId = UUID.randomUUID().toString();
        log.info("----------外部接口请求开始 id:【{}】, 接口名称【{}】,请求地址:【{}】,请求参数:【{}】----------", requestId, msg.getTitle(), url, msg.getBody());
        try {
            SysOperLogApiDO apiLog = new SysOperLogApiDO();
            String body = HttpRequest.post(url)
                    .headerMap(header, false)
                    .body(AesUtil.aesEncrypt(msg.getBody(), key))
                    .execute().body();
            stopWatch.stop();
            long totalTimeMillis = stopWatch.getTotalTimeMillis();
            log.info("----------外部接口请求结束 id:【{}】, 耗时:【{}】ms----------", requestId, totalTimeMillis);
            AssertUtil.assertTrue(StringUtils.isNotBlank(body), SysCode.EXTERNAL_API_ERROR);
            if (JSON.isValid(body)) {
                JSONObject bodyData = JSON.parseObject(body);
                throw new ServiceException(bodyData.getIntValue("code"), bodyData.getString("msg"));
            }
            if(body.contains("<html>")){
                throw new ServiceException(500000, "请确认接口次数");
            }
            BaseApiResponseMsg responseMsg = JSON.parseObject(AesUtil.aesDecrypt(body, key), BaseApiResponseMsg.class);
            if (ObjectUtils.isEmpty(responseMsg) || ObjectUtils.isEmpty(responseMsg.getCode())) {
                throw new ServiceException(SysCode.EXTERNAL_API_ERROR);
            } else if (SUCCESS_CODE != responseMsg.getCode()) {
                throw new ServiceException(responseMsg.getCode(), responseMsg.getMsg());
            }

            apiLog.setTitle(msg.getTitle());
            apiLog.setUrl(url);
            apiLog.setParam(msg.getBody());
            apiLog.setStatus(responseMsg.getCode().toString());
            apiLog.setType(SearchType.getValue(msg.getType()));
            apiLog.setDescription(msg.getDescription());
            logApiDao.save(apiLog);
            return responseMsg;
        } catch (ServiceException e) {
            throw e;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new ServiceException(SysCode.EXTERNAL_API_ENCODE_OR_DECODE_ERROR);
        }
    }

    @Override
    public BaseApiResponseMsg emitHttpRequestNotEncrypt(BaseApiRequestMsg msg) throws ServiceException {
        String url = IP + msg.getUrl();

        Map<String, String> header = new HashMap<>(8);
        header.put("Content-Type", HEADER_CONTENT_TYPE);
        header.put("ticket", HEADER_TICKET);

        log.info("---------- 接口名称【{}】,请求地址:【{}】,请求参数:【{}】----------", msg.getTitle(), url, msg.getBody());
        try {
            String body = HttpRequest.post(url)
                    .headerMap(header, false)
                    .body(msg.getBody())
                    .execute().body();
            AssertUtil.assertTrue(StringUtils.isNotBlank(body), SysCode.EXTERNAL_API_ERROR);
            BaseApiResponseMsg responseMsg = JSON.parseObject(body, BaseApiResponseMsg.class);
            log.info("请求接口：【{}】,请求结果:【{}】", msg.getTitle(), responseMsg);
            if (ObjectUtils.isEmpty(responseMsg) || ObjectUtils.isEmpty(responseMsg.getCode())) {
                throw new ServiceException(SysCode.EXTERNAL_API_ERROR);
            } else if (SUCCESS_CODE != responseMsg.getCode()) {
                throw new ServiceException(responseMsg.getCode(), responseMsg.getMsg());
            }
            return responseMsg;
        } catch (ServiceException e) {
            throw e;
        } catch (Exception e) {
            throw new ServiceException(SysCode.EXTERNAL_API_ENCODE_OR_DECODE_ERROR);
        }
    }

}

